package com.teamizer.server;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Random;

import com.google.gwt.user.server.rpc.RemoteServiceServlet;
import com.teamizer.client.GreetingService;

/**
 * The server side implementation of the RPC service.
 */
@SuppressWarnings("serial")
public class GreetingServiceImpl extends RemoteServiceServlet implements
		GreetingService {
	
	private Random random = new Random(System.currentTimeMillis());

	public String greetServer(String input) {
		String serverInfo = getServletContext().getServerInfo();
		String userAgent = getThreadLocalRequest().getHeader("User-Agent");
		return "Hello, " + input + "!<br><br>I am running " + serverInfo
				+ ".<br><br>It looks like you are using:<br>" + userAgent;
	}

	@Override
	public String teamizePlayers(ArrayList<String> players, ArrayList<String> teams) {
		try {
			Thread.sleep(10000);
		} catch (InterruptedException e) {
			e.printStackTrace();
		}
		ArrayList<String> playersAux = players;
		HashMap<String, ArrayList<String>> playerTeamized = new HashMap<String, ArrayList<String>>();
		int playerCount = 0;
		while ( playersAux.size() > 0) {
			ArrayList<String> teamToAssign = playerTeamized.get(teams.get(playerCount%teams.size()));
			if (teamToAssign == null) {
				teamToAssign = new ArrayList<String>();
				playerTeamized.put(teams.get(playerCount%teams.size()), teamToAssign);
			}
			int playerPosition = calculateRandom(playersAux.size());
			String playerToAssign = playersAux.get(playerPosition);
			
			teamToAssign.add(playerToAssign);
			
			playersAux.remove(playerPosition);
			playerCount++;
		}
		
		StringBuilder result = new StringBuilder();
		Iterator<String> teamNames = playerTeamized.keySet().iterator();
		while(teamNames.hasNext()) {
			String teamName = teamNames.next();
			result.append("<b>");
			result.append(teamName);
			result.append("</b>");
			result.append("<br>");
			ArrayList<String> team = playerTeamized.get(teamName);
			for (int i = 0; i<team.size(); i++) {
				result.append(team.get(i));
				result.append("<br>");
			}
		}
		
		return result.toString();
	}
	
	public int calculateRandom(int maxValue) {
		int rc = 0;
		
		rc = random.nextInt(maxValue);
		
		return rc;
	}

	@Override
	public String getAnnounce() {
		return "res/qrcode.png";
	}
}
